import { Cartesian2, Color, createPropertyDescriptor, Material, Property } from '@space8/czm-plugin';
import MaterialProperty from './MaterialProperty.js';

class PolylineTrailMaterialProperty extends MaterialProperty {
  constructor(options = {}) {
    super(options);
  }

  getType(time) {
    return Material.PolylineTrailType;
  }

  getValue(time, result) {
    if (!result) {
      result = {};
    }
    result.color = Property.getValueOrUndefined(this._color, time);
    result.speed = this._speed;
    return result;
  }

  equals(other) {
    return (
      this === other ||
      (other instanceof PolylineTrailMaterialProperty &&
        Property.equals(this._color, other._color) &&
        Property.equals(this._speed, other._speed))
    );
  }
}

Object.defineProperties(PolylineTrailMaterialProperty.prototype, {
  color: createPropertyDescriptor('color'),
  speed: createPropertyDescriptor('speed'),
});

Material.PolylineTrailType = 'PolylineTrail';
Material._materialCache.addMaterial(Material.PolylineTrailType, {
  fabric: {
    type: Material.PolylineTrailType,
    uniforms: {
      color: new Color(1.0, 0.0, 0.0, 0.7),
      image: Material.DefaultImageId,
      speed: 1,
      repeat: new Cartesian2(1, 1),
    },
    source: `
      uniform vec4 color;
      uniform float speed;
      
      czm_material czm_getMaterial(czm_materialInput materialInput){
         czm_material material = czm_getDefaultMaterial(materialInput);
         vec2 st = materialInput.st;
         float time = fract(czm_frameNumber * speed / 1000.0);
         material.diffuse = color.rgb;
         material.alpha = color.a * fract(st.s-time);
         return material;
      }
    `,
  },
  translucent: function (material) {
    return true;
  },
});

export default PolylineTrailMaterialProperty;
